package br.com.commons.utility.datatable.builder.sql;

import java.util.ArrayList;
import java.util.List;

public abstract class DataTableSQLBuilder {

	private List<String> listColumns;
	private List<String> listFrom;
	private List<String> listWhere;
	private List<String> listOrderBy;
	private List<String> listExtra;
	
	protected Object[] attributes;
	
	protected void addColumns(String column){
		listColumns.add(column);
	}
	
	protected void addFrom(String from){
		listFrom.add(from);
	}
	
	protected void addWhere(String where){
		listWhere.add(where);
	}
	
	protected void addOrderBy(String orderBy){
		listOrderBy.add(orderBy);
	}
	
	protected void addExtra(String extra){
		listExtra.add(extra);
	}
	
	public String execute(Object... attributes){
		this.attributes = attributes;
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT ").append(addColumns());
		sql.append(" FROM ").append(addFrom());
		sql.append(addWhere());
		sql.append(addOrderBy());
		sql.append(addExtra());
		return sql.toString();
	}
	
	private String addColumns() {
		listColumns = new ArrayList<String>();
		builderColumns();		
		StringBuilder sql = new StringBuilder();
		for (int i = 0; i < listColumns.size(); i++) {
			if(i > 0) { sql.append(","); }
			sql.append(" ").append(listColumns.get(i));
		}
		return sql.toString();
	}
	
	private String addFrom() {
		listFrom = new ArrayList<String>();
		builderFrom();
		StringBuilder sql = new StringBuilder();
		for (int i = 0; i < listFrom.size(); i++) {
			if(i > 0) { sql.append(","); }
			sql.append(" ").append(listFrom.get(i));
		}
		return sql.toString();
	}
	
	private String addWhere() {
		listWhere = new ArrayList<String>();
		builderWhere();
		if(listWhere.isEmpty()) { return ""; }
		StringBuilder sql = new StringBuilder(" WHERE ");
		for (int i = 0; i < listWhere.size(); i++) {
			sql.append(" ").append(listWhere.get(i)).append(" ");
		}
		return sql.toString();
	}
	
	private String addOrderBy() {
		listOrderBy = new ArrayList<String>();
		builderOrderBy();
		if(listOrderBy.isEmpty()) { return ""; }
		StringBuilder sql = new StringBuilder(" ORDER BY ");
		for (int i = 0; i < listOrderBy.size(); i++) {
			if(i > 0) { sql.append(","); }
			sql.append(" ").append(listOrderBy.get(i));
		}
		return sql.toString();
	}
	
	private String addExtra() {
		listExtra = new ArrayList<String>();
		builderExtra();
		if(listOrderBy.isEmpty()) { return ""; }
		StringBuilder sql = new StringBuilder();
		for (int i = 0; i < listExtra.size(); i++) {
			sql.append(" ").append(listExtra.get(i)).append(" ");
		}
		return sql.toString();
	}
	
	protected abstract void builderColumns();
	protected abstract void builderFrom();
	protected abstract void builderWhere();
	protected abstract void builderOrderBy();
	protected abstract void builderExtra();
}
